package com.zhangxun.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangxun.constant.AuthConstant;
import com.zhangxun.domain.SysUser;
import com.zhangxun.domain.WxUser;
import com.zhangxun.mapper.SysUserMapper;
import com.zhangxun.mapper.WxUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WxUserMapper wxUserMapper;


    @Value("${wx.url}")
    private String url;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户发送的请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //从请求头中获取登录用户的类型
        String type = request.getHeader(AuthConstant.LOGIN_TYPE);

        UserDetails userDetail = null;//定义返回的对象
        switch (type){
            //系统用户
            case AuthConstant.SYS_USER:
                SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username",username));
                List<String> perms =  sysUserMapper.selectPermsById(sysUser.getUserId());
                sysUser.setPerms(perms);
                userDetail = sysUser;
                break;
            //网络用户
            case AuthConstant.MEMBER:
                //将appid传入地址的string字符串中
                String remoteUrl = String.format(url,username);
                String result = HttpUtil.get(remoteUrl); //实现远程调用获取openid；

                //获取openid；
                JSONObject jsonObject = JSON.parseObject(result);
                String userId = jsonObject.getString("openid");
                if(StringUtils.isEmpty(userId)){
                    throw new RuntimeException("获取openid失败，请检查请求地址");
                }

                //查询数据库是否有用户
                WxUser wxUser = wxUserMapper.selectById(userId);

                //如果没有就创建一个并保存数据库，然后返回。
                if(ObjectUtil.isEmpty(wxUser)){
                    wxUser = new WxUser();
                    wxUser.setUserId(userId);
                    wxUser.setUserRegetime(new Date());
                    wxUser.setUserLastip(request.getRemoteAddr());
                    wxUserMapper.insert(wxUser);
                }
                userDetail = wxUser;

                break;
        }

        return userDetail;
    }
}
